<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <!--<el-form-item label="排产状态" prop="wplanStatus">
        <el-select v-model="queryParams.wplanStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in planStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品编码" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handlePlan('MULITPLE', {})"
          v-hasPermi="['orderplan:pending:edit']"
        >执行排产（当前选择)</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handlePlanOfAll('ALL')"
          v-hasPermi="['orderplan:pending:edit']"
        >执行排产（符合条件）</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="openPendingDrawer"
        >继续处理待排产数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              show-summary
              border style="width:100%;" ref="multipleTable" :data="newOrderPlanList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  :selectable="handleDisable"/>
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="合同编号" align="center" prop="contractCode" width="120" />
      <el-table-column label="订单日期" align="center" prop="orderDate" width="100"/>
      <el-table-column label="分单日期" align="center" prop="createDate" width="100" />
      <el-table-column label="产地" align="center" prop="factoryName" width="120px" :show-overflow-tooltip="true" />
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <el-table-column label="工单编号" align="center" prop="workerorderCode" width="200" />
      <el-table-column label="产品编码" align="center" prop="bomCode" width="120" />
      <el-table-column label="产品名称" align="center" prop="bomName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" align="center" prop="productStandard" :show-overflow-tooltip="true"/>
      <el-table-column label="产品单位" align="center" prop="productUnit"  width="80px"/>
      <el-table-column label="产品数量" align="center" prop="productNum"  width="80px"/>
      <el-table-column label="采样数量" align="center" prop="sampleNum" />
      <el-table-column label="分单数量" align="center" prop="workerOrdernum" />
      <el-table-column label="要求完成日期" align="center" prop="order_finishdate" width="100">
        <template slot-scope="scope">
          {{ formatDateToYYYYMMDD(scope.row.order_finishdate) }}
        </template>
      </el-table-column>
      <el-table-column label="是否缺料" align="center" prop="missingMaterail" width="100"/>
      <!--<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.storeStatus == '0'"
            @click="handlePlan('SINGLE', scope.row)"
            v-hasPermi="['factory:factorywplan:edit']"
          >执行排产</el-button>
          &lt;!&ndash;<el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.wplanStatus == '1'"
            @click="handlePrint(scope.row)" v-hasPermi="['factory:factorywplan:edit']">打印工单</el-button>&ndash;&gt;
        </template>
      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog title="产品总部排产" :visible.sync="open" width="1650px" :close-on-click-modal ="false" append-to-body>
      <!-- 数据统计 -->
      <div style="clear: both;margin-bottom: 30px;">
        <el-row :gutter="26">
          <el-col :span="3">
            <div>
              <el-statistic title="所选班组">
                <template slot="formatter">{{ teamName }}</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic title="已选数量">
                <template slot="formatter">{{selectedCount}}条</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="standardCapacity" title="标准产能/天"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="totalStandardCapacity" title="总标准产能" />
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="restCapacity" title="总剩余产能"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="needCapacity" title="所需产能"/>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="float: left; clear: both;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px"  style="margin-bottom: 10px">
          <!--<el-date-picker clearable
            v-model="form.weekStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期">
          </el-date-picker>
          -
          <el-date-picker clearable
            v-model="form.weekEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期">
          </el-date-picker>-->
          <!--<el-button type="primary" @click="printPlan" style="margin-left: 20px;">打印周计划</el-button>-->
          <el-button type="primary" @click="excutePlan" style="margin-right: 20px;">排产计算</el-button>
        </el-form>
      </div>
      <template v-for="planItem in wplanProductVOList">
        <div style="margin-right: 5px;margin-top: 10px;">
          <!--<el-tag :type="planItem.typeTag" size="medium"  effect="light" style="margin-right: 25px;">
            合同号：{{planItem.contractCode}} | 产品编码：{{planItem.productCode}} | 产品名称：{{planItem.productName}}
          </el-tag>-->
          <el-descriptions class="margin-top" title="" :column="3" size="small" border>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-check"></i>
                合同号
              </template>
              {{planItem.contractCode}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-order"></i>
                产品编码|产品名称
              </template>
              <el-tag type="danger">{{planItem.productCode}} | {{planItem.productName}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-order"></i>
                标签或包装选择
              </template>
              <el-checkbox v-model="planItem.labelCheckAll" @change="labelCheckAllChange(planItem)">标签文档全选</el-checkbox>
              <el-checkbox v-model="planItem.packageCheckAll" @change="packageCheckAllChange(planItem)">包装单全选</el-checkbox>
              <el-checkbox v-model="planItem.bothOfCheckAll" @change="bothOfCheckAllChange(planItem)">两者同时全选</el-checkbox>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-table
          style="width: 100%"
          row-key="id"
          show-summary
          border
          lazy
          v-loading="loading2"
          :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="planItem.wplanList" >
          <el-table-column label="子项物料编码" align="center" prop="bomCode"  width="160px" />
          <el-table-column label="物料名称" align="center" prop="bomName" />
          <el-table-column label="规格型号" align="center" prop="productStandard" />
          <el-table-column label="订单合同号" align="center" prop="contractCode" />
          <el-table-column label="订单日期" align="center" prop="orderDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="标签文档" align="center" class-name="small-padding fixed-width" prop="labelCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.labelCheck"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="包装单" align="center" class-name="small-padding fixed-width" prop="packageCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.packageCheck"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="订单数量" align="center" prop="orderNum" />
          <el-table-column label="分单数量" align="center" prop="workerOrdernum" width="90px"/>
          <el-table-column label="库存" align="center" prop="storeNum" width="90px"/>
          <el-table-column label="待排产数量" align="center" prop="planNum" width="90px"/>
          <!--          <el-table-column label="排产数量" align="center" prop="planCapacity"  width="110px">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-tag type="success" v-if="scope.row.planCapacity!=null">{{scope.row.planCapacity}} {{scope.row.bomUnit == null ? '' : scope.row.bomUnit}}</el-tag>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="排产情况" align="center" prop="capacityDesc" width="100px"/>
          <el-table-column label="排产开始时间" align="center" prop="planStartDate"  width="100px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排产结束时间" align="center" prop="planEndDate"  width="100px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否缺料" align="center" prop="missingMaterail" />

          <!-- 此功能后续优化上线再放开，请勿删除这个逻辑 -->
          <!--<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80px" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAdjust(scope.row)"
              >调整</el-button>
              &lt;!&ndash;<el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.levelValue===1"
                v-hasPermi="['order:plan:adjust']"
                @click="handPlanRemoveOrder(scope.row)"
              >移除</el-button>&ndash;&gt;
            </template>
          </el-table-column>-->
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitPlan" >提交排产</el-button>
      </div>
    </el-dialog>

    <!-- 排产调整对话框 -->
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
      <div style="margin-bottom: 20px;text-align: center;">
        <el-row :gutter="16">
          <el-col :span="4" style="margin-right: 100px;">
            <div>
              计划开始日期：
              <el-date-picker
                clearable
                v-model="adjustWplanSelected.planStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="计划开始日期"
                @change="wplanDateChange"
              >
              </el-date-picker>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              计划结束日期：
              <el-date-picker
                clearable
                v-model="adjustWplanSelected.planEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="计划结束日期"
                @change="wplanDateChange"
              >
              </el-date-picker>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="adjustWplanSelected.detailList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="排产日期" align="center" prop="planDate" width="300">
          <template slot-scope="scope">
            <el-date-picker
              clearable
              v-model="scope.row.planDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="排产数量" align="center" prop="planCapacity" width="200px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.planCapacity" placeholder="排产数量" clearable ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.$index>0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="wplanDateRemove(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 未完成的分单排产数据 -->
    <el-drawer
      title="已分单待排产明细"
      :visible.sync="pendingPlanVisible"
      direction="rtl"
      size="55%">
      <el-row :gutter="10" class="mb8" style="margin-left: 5px;">
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="selectedPendingHandle">选中去排产</el-button>
        </el-col>
      </el-row>
      <el-table :data="pendingOrderList"
                border style="width:100%;"
                ref="multipleTable"
                @selection-change="handlePendingSelectionChange">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column label="合同号" align="center" prop="contractCode" />
        <el-table-column label="订单号" align="center" prop="orderCode" />
        <el-table-column label="分厂名称" align="center" prop="factoryName" />
        <el-table-column label="班组名称" align="center" prop="teamName" width="120px"/>
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品数量" align="center" prop="productNum" width="80px"/>
        <el-table-column label="已分单数量" align="center" prop="workerOrdernum" width="90px"/>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import { newPendingList, pendingGroupList, pendingGroupListOfAll, excuteNewPlan, submitNewPlan  } from "@/api/sm/order/orderplan";
import { listTeam,listFactory } from "@/api/system/dept";
import { listChildren } from "@/api/sm/basic/bominfo";
import moment from "moment";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      teamSelect: true,
      planCal: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      // TODO newplan
      newOrderPlanList: [],
      //分厂待排产订单信息表格数据
      factoryWorkOrderList: [],
      factoryList: [],
      teamList: [],
      adjustWplanSelected: {},
      // 废弃
      adjustdetailList: [],
      //排产工单
      wplanProductVOList: [],
      //排产结果
      planResultList: [],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        },
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adjustopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: null,
        orderCode: null,
        bomCode: null,
        bomName: null,
        teamId: null,
        excludeIds: [],
      },
      // 表单参数
      form: {
        teamId: null,
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      },
      // 表单参数
      form1: {
        orderPlanList: null
      },
      form2: {
        mId: null,
        planStartDate: null,
        planEndDate: null
      },
      // 表单校验
      rules: {
      },
      // 统计数据
      teamName: "-",
      selectedCount: 0,
      standardCapacity: 0,
      totalStandardCapacity: 0,
      restCapacity: 0,
      needCapacity: 0,
      action: null,

      pendingPlanVisible: false,
      selectedPendingList: [],
      // 临时分单集合数据
      splitWorkOrderList:[],
      // 临时待处理的数据
      pendingOrderList: [],
      uuidParam: null,
    };
  },
  created() {
    this.getFactoryList();
    // this.getList();
    // 从外部传入的 uuid key，指向具体数据，目前从批量分单过来
    const p = this.$route.query && this.$route.query.p;
    console.log("参数=", p);
    if (p) {
      this.uuidParam = p;
      const item = localStorage.getItem(`split_${p}`);
      if (item) {
        this.splitWorkOrderList = JSON.parse(item);
        console.log("参数值=", this.splitWorkOrderList);
        this.handlePlanOfJumpToThis(this.splitWorkOrderList);
      }
    }
  },
  methods: {
    formatDateToYYYYMMDD(date) {
      if (date) {
        return moment(date).format('YYYY-MM-DD');
      }
      return "";
    },
    wplanDateRemove(row) {
      let wplanList = this.adjustWplanSelected.detailList;
      if (wplanList.length === 0) {
        alert('已经无日期删除');
      }
      for(let i=0;i<wplanList.length;i++) {
        let obj = wplanList[i];
        if (obj.planDate === row.planDate) {
          wplanList.splice(i, 1);
          break;
        }
      }
    },
    wplanDateChange() {
      let detailList = this.adjustWplanSelected.detailList;
      if (detailList.length === 0) {
        alert('已经无日期调整');
      }
      let cloneSrcObject = this.adjustWplanSelected.detailList[0];

      const newStart = new Date(this.adjustWplanSelected.planStartDate);
      const newEnd = new Date(this.adjustWplanSelected.planEndDate);

      let preStart = new Date(this.adjustWplanSelected.detailList[0].planDate);
      let preEnd = new Date(this.adjustWplanSelected.detailList[this.adjustWplanSelected.detailList.length-1].planDate);

      // 调整结束日期，循环变量从起始日期开始，逐天增加
      while (newEnd > preEnd) {
        preEnd.setDate(preEnd.getDate() +1);
        let curPlanDate = this.formatDateToYYYYMMDD(preEnd);
        const exists = this.adjustWplanSelected.detailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.detailList.push(rowWPlan);
        }
      }

      // 调整开始日期
      while (newStart < preStart) {
        preStart.setDate(preStart.getDate() -1);
        let curPlanDate = this.formatDateToYYYYMMDD(preStart);
        const exists = this.adjustWplanSelected.detailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.detailList.unshift(rowWPlan);
        }
      }
    },
    labelCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.labelCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
      console.log("planItem", planItem);
    },
    packageCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.packageCheck = planItem.packageCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
    },
    bothOfCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.bothOfCheckAll;
        wplan.packageCheck = planItem.bothOfCheckAll;
      }
      planItem.labelCheckAll = planItem.bothOfCheckAll;
      planItem.packageCheckAll = planItem.bothOfCheckAll;
    },

    /** 调整排产日期功能 提交按钮 */
    submitAdjustForm() {

      if(this.adjustWplanSelected.planFinishdate<this.adjustWplanSelected.planStartdate){
        this.$modal.msgError("排产完成时间不能小于排产开始时间");
        return;
      }
      this.adjustopen = false;
    },
    cancel2() {
      this.adjustopen = false;
      this.reset2();
    },
    reset2(){
      this.form2 = {
        mId: null,
        planStartDate: null,
        planEndDate: null
      };
      this.resetForm("form2");
    },
    handleAdjust(row) {
      this.reset2();
      console.log("计算之后的 row", row);
      this.adjustWplanSelected = row;
      this.adjustopen = true;
    },
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        if (res.data && res.data.length === 0) {
          this.$modal.msgError(`${tree.bomCode}|${tree.bomName}, 未加载到子项物料数据`);
        }
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },

    //打印周计划
    printPlan() {
      if(this.planCal==false){
        alert("请先排产,再打印周计划");
        return;
      }

      this.form1.wplanList=[];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          this.form1.wplanList.push(cur);
        }
      }

      printPlan(this.form1).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '周排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },

    getFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.factoryList = response.data;

        // TODO 需要注释掉的，方便测试
        this.queryParams.factoryId = this.factoryList[0].deptId;
        this.teamList = [];
        this.getTeamList(this.queryParams.factoryId);

        this.loading = false;
      });
    },
    factoryChange() {
      if (!this.queryParams.factoryId) {
        this.teamList = [];
        return;
      }
      this.getTeamList(this.queryParams.factoryId);
    },
    /** 查询订单信息列表 */
    getTeamList(parentId) {
      this.loading = true;
      listTeam({"parentId":parentId}).then(response => {
        this.teamList = response.data || [];

        // TODO 方便测试，需要注释掉
        // this.queryParams.teamId = this.teamList[1].deptId;

        this.loading = false;
      });
    },

    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printWplanWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '月排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    getThisSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 6 - currentDay;
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekStartDate=currentDate;
    },
    getNextSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 13 - (currentDay+1);
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekEndDate=currentDate;
    },
    handleDisable(row, index) {
      if (row.wplanStatus == '1') {
        return false
      } else {
        return true
      }
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      newPendingList(this.queryParams).then(response => {
        this.newOrderPlanList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      };
      this.resetForm("form");
    },
    reset1() {
      this.form1 = {
        wplanList: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.excludeIds = [];
      this.queryParams.pageNum = 1;
      if(this.queryParams.teamId!=null && this.queryParams.teamId!=undefined){
        this.teamSelect = false;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    validate(action) {
      if (!this.queryParams.factoryId) {
        this.$modal.msgError("分厂未选择，无法进行排产");
        return true;
      }
      if (!this.queryParams.teamId) {
        this.$modal.msgError("分厂班组未选择，无法进行排产");
        return true;
      }
      if (action === "ALL") {
        // TODO
      } else {
        if (!this.ids || this.ids.length === 0) {
          this.$modal.msgError("未选择任何工单，无法进行排产");
          return true;
        }
      }
      return false;
    },
     /** 执行排产操作 */
    handlePlan(action, row) {
      if (this.validate(action)) {
        return;
      }
      this.open = true;
      this.action = action;
      this.reset();
      this.reset1();
      // this.getThisSaturday();
      // this.getNextSaturday();
      this.loading2 = true;
      const ids = row.id || this.ids;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      pendingGroupList({"ids":ids+'',"teamId":this.queryParams.teamId}).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        this.planCal = false;
        this.loading2 = false;

        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
      });
    },
    handlePlanOfAll(action) {
      if (this.validate(action)) {
        return;
      }
      this.action = action;
      if (this.action === 'ALL') {
        this.queryParams.excludeIds = [];
      }
      this.reset1();
      this.loading2 = true;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      pendingGroupListOfAll(this.queryParams).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        this.planCal = false;
        this.loading2 = false;

        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.workOrderNum);
        this.needCapacity = new Number(response.data.needCapacity);
      }).catch((error) => {
        this.open = false;
        this.planCal = false;
        this.loading2 = false;
      });
    },
    groupByConditions(objects) {
      return objects.reduce((acc, obj) => {
        // 构造用于分组的 key
        const key = `${obj.factoryId}_${obj.teamId}_${obj.productCode}_${obj.contractCode}`;
        // 如果 acc[key] 不存在，则初始化为空数组
        if (!acc[key]) {
          acc[key] = [];
        }
        // 将当前对象添加到对应的分组中
        acc[key].push(obj);
        return acc;
      }, {});
    },
    openPendingDrawer() {
      this.pendingPlanVisible = true;
    },
    handlePendingSelectionChange(selection) {
      this.selectedPendingList = selection.map((item) => item);
    },
    selectedPendingHandle() {
      if (this.selectedPendingList.length === 0) {
        this.$modal.msgError(`未选择数据，无法进行去排产操作`);
        return;
      }
      // 参数构建
      const batchQueryParams = {
        contractNoList: [],
        productCodeList: [],
      };
      let nextFactoryId = this.selectedPendingList[0].factoryId;
      let nextTeamId = this.selectedPendingList[0].teamId;
      for (let selected of this.selectedPendingList) {
        batchQueryParams.factoryId = selected.factoryId;
        batchQueryParams.teamId = selected.teamId;
        if (nextFactoryId !== selected.factoryId) {
          this.$modal.msgError(`存在选择多个不同分厂${selected.factoryName}的数据，无法同时进行排产，请重新选择`);
          return;
        }
        if (nextTeamId !== selected.teamId) {
          this.$modal.msgError(`存在选择多个不同班组${selected.teamName}的数据，无法同时进行排产，请重新选择`);
          return;
        }
        nextFactoryId = selected.factoryId;
        nextTeamId = selected.teamId;
        batchQueryParams.contractNoList.push(selected.contractCode);
        batchQueryParams.productCodeList.push(selected.productCode);
      }
      this.handlePlanFullLink(batchQueryParams);
    },
    handlePlanOfJumpToThis(params) {
      // 参数构建
      const batchQueryParams = {
        contractNoList: [],
        productCodeList: [],
      };
      const bomItemList = [];
      for (let splitOrder of params) {
        if (splitOrder.bomSubmitVOList) {
          for (let bom of splitOrder.bomSubmitVOList) {
            bomItemList.push(bom);
          }
        }
        batchQueryParams.contractNoList.push(splitOrder.contractCode);
        batchQueryParams.productCodeList.push(splitOrder.productCode);
      }
      // 进行分组，分厂+班组+合同号+产品
      const grouped = this.groupByConditions(bomItemList);
      const numOfGroups = Object.keys(grouped).length;
      // 如果只有一组，则直接排产
      if (numOfGroups === 1) {
        const value = Object.values(grouped)[0];
        batchQueryParams.factoryId = value[0].factoryId;
        batchQueryParams.teamId = value[0].teamId;
      } else {
        // 如果有多组，则需要弹出框，让用户选择那一组先排产
        Object.keys(grouped).forEach(key => {
          const bom = grouped[key][0];
          this.pendingOrderList.push(Object.assign({}, bom));
        });
        // TODO 弹出抽屉，让用户选择先操作哪个一个
        this.openPendingDrawer();
        return;
      }
      this.handlePlanFullLink(batchQueryParams);
    },
    handlePlanFullLink(batchQueryParams) {
      this.loading2 = true;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      pendingGroupListOfAll(batchQueryParams).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        this.planCal = false;
        this.loading2 = false;

        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.workOrderNum);
        this.needCapacity = new Number(response.data.needCapacity);
      }).catch((error) => {
        this.open = false;
        this.planCal = false;
        this.loading2 = false;
      });
    },

    handPlanRemoveOrder(row) {
      const id = row.id
      for(let i =0; i<this.wplanProductVOList.length; i++) {
        let obj = this.wplanProductVOList[i];
        obj.wplanList.map((item, index) => {
          if (item.id === id) {
            obj.wplanList.splice(index, 1);
            this.queryParams.excludeIds.push(id);
          }
        });
        // 判断一个半成品也没有了
        if (obj.wplanList.length === 0) {
          this.wplanProductVOList.splice(i, 1);
        }
      }
      if (this.wplanProductVOList.length === 0) {
        this.$modal.msgSuccess("仅有一个产品都被删除了，分厂周排产窗口被关闭");
        this.open = false;
        this.queryParams.excludeIds = [];
        return;
      }
      // 只有多选才会删除表中数据
      if (this.action === 'MULTIPLE') {
        // 重新计算开始
        for (let i = 0; i < this.factoryWorkOrderList.length; i++) {
          let cur = this.factoryWorkOrderList[i];
          if (cur.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(this.factoryWorkOrderList[i], false);
            break;
          }
        }
        // 计算后的数据，如果存在也要移除
        for (let i = 0; i < this.ids.length; i++) {
          if (this.ids[i] === id) {
            this.ids.splice(i, 1);
            break;
          }
        }
        // 重新做排产计算
        this.handlePlan(this.action,{});
      } else {
        this.handlePlanOfAll('ALL_DELETE');
      }
    },

    excutePlan() {
      if(this.wplanProductVOList.length==0){
        alert("无排产工单");
        return;
      }
      let planWorkOrderList = [];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          planWorkOrderList.push(cur);
        }
      }
      this.loading2 = true;
      this.form.teamId = this.queryParams.teamId;
      this.form.workorderIds = planWorkOrderList.map(item => item.id).join(',');
      excuteNewPlan(this.form).then(response => {
        // TODO
        this.wplanProductVOList = response.data || [];

        console.log("排产计算返回", response);

        this.$modal.msgSuccess("排产成功");

        // this.teamName = response.data.teamName;
        // this.selectedCount = this.wplanProductVOList.length;
        // this.standardCapacity = new Number(response.data.standardCapacity);
        // this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        // this.restCapacity = new Number(response.data.nextCapacity);
        // this.needCapacity = new Number(response.data.needCapacity);

        this.planCal = true;
        this.loading2 = false;
      }).catch((error) => {
        // this.$modal.msgError(error.message);
        this.planCal = true;
        this.loading2 = false;
        console.log("发送异常:", error);
      });
    },

    submitPlan() {
      if(this.planCal==false){
        this.$modal.msgError("请先做排产计算,再提交");
        return;
      }
      this.$modal.confirm('确认要提交产品排产计划，提交保存吗?').then(() => {
        const loading = this.$loading({
          lock: true,
          text: '排产数据提交中，请耐心等待计算结果～感谢',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.form1.orderPlanList=[];
        this.form1.orderPlanList=[];
        for(let obj of this.wplanProductVOList) {
          this.form1.orderPlanList.push(...(obj.wplanList || []));
        }
        console.log("提交排产", this.form1);
        submitNewPlan(this.form1).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.open = false;
          this.getList();
          // TODO 新增加的内容
          this.removePendingList();
          loading.close();
        }).catch((error) => {
          loading.close();
          this.open = false;
        });
      }).then(() => {
      }).catch(() => {
          this.open = false;
          loading.close();
      });
    },

    removePendingList() {
      // 需要删除悬浮中待排产中的数据
      if (this.selectedPendingList && this.selectedPendingList.length > 0) {
        const removeItem = [];
        for (let i=0; i < this.pendingOrderList.length;i++) {
          const pending = this.pendingOrderList[i];
          const findObj = this.selectedPendingList.find(item =>
            item.factoryId === pending.factoryId &&
            item.teamId === pending.teamId &&
            item.contractCode === pending.contractCode &&
            item.productCode === pending.productCode);
          if (findObj) {
            removeItem.push(i);
          }
        }
        for (let i = removeItem.length - 1; i >= 0; i--) {
          this.pendingOrderList.splice(removeItem[i], 1);
        }
        if (this.uuidParam) {
          if (this.pendingOrderList.length === 0) {
            localStorage.removeItem(`split_${this.uuidParam}`);
          } else {
            const removeSplit = [];
            for (let obj of this.selectedPendingList) {
              for (let i=0; i < this.splitWorkOrderList.length;i++) {
                const split = this.splitWorkOrderList[i];
                const findObj = split.bomSubmitVOList.find(item =>
                  item.factoryId === obj.factoryId &&
                  item.teamId === obj.teamId &&
                  split.contractCode === obj.contractCode &&
                  split.productCode === obj.productCode);
                if (findObj) {
                  removeSplit.push(i);
                }
              }
            }
            for (let i = removeSplit.length - 1; i >= 0; i--) {
              this.splitWorkOrderList.splice(removeSplit[i], 1);
            }
            localStorage.setItem(`split_${this.uuidParam}`, JSON.stringify(this.splitWorkOrderList));
          }
        }
      }
    },
  }
};
</script>
